package com.p6spy.engine.config;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库配置
 */
public class DatabaseConfig {

    private static final String PROPERTIES_FILE = "db.properties";

    private static String url = null;
    private static String user = null;
    private static String password = null;

    /*
     * 文件的读取，只需要读取一次即可拿到这些值。使用静态代码块
     */
    static {
        //读取资源文件，获取值。
        try {
            //1. 创建Properties集合类。
            Properties pro = new Properties();
            ClassLoader classLoader = DatabaseConfig.class.getClassLoader();
            URL res = classLoader.getResource(PROPERTIES_FILE);
            assert res != null;
            String path = res.getPath();
            System.out.println(path);

            //2. 加载文件
            pro.load(new FileReader(path));

            //3. 获取数据，赋值
            url = pro.getProperty("db.url");
            user = pro.getProperty("db.user");
            password = pro.getProperty("db.password");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
